<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryRef"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
            <el-form-item label="文件分类" prop="categoryId">
                <div style="width: 180px">
                    <el-tree-select
                        v-model="queryParams.categoryId"
                        :data="categoryTreeOptions"
                        :props="{
                            value: 'id',
                            label: 'categoryName',
                            children: 'children'
                        }"
                        value-key="id"
                        placeholder="请选择文件分类"
                        check-strictly
                        clearable
                    />
                </div>
            </el-form-item>

            <el-form-item label="文件名称" prop="name">
                <el-input
                    v-model="queryParams.name"
                    placeholder="请输入文件名称"
                    clearable
                    @keyup.enter="handleQuery"
                />
            </el-form-item>

            <el-form-item label="VIP专享" prop="isVip">
                <el-select
                    v-model="queryParams.isVip"
                    placeholder="请选择VIP专享"
                    style="width: 180px"
                    clearable
                >
                    <el-option label="全部" :value="null" />
                    <el-option label="是" :value="true" />
                    <el-option label="否" :value="false" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery"
                    >搜索</el-button
                >
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-card class="base-table" ref="fullTable">
            <TableSetup
                ref="tSetup"
                @onStripe="onStripe"
                @onRefresh="onRefresh"
                @onChange="onChange"
                @onfullTable="onfullTable"
                @onSearchChange="onSearchChange"
                :columns="columns"
                :isTable="isTable"
            >
                <template v-slot:operate>
                    <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['bg:file:add']"
                        >新增</el-button
                    >
                    <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['bg:file:edit']"
                        >修改</el-button
                    >
                    <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['bg:file:remove']"
                        >删除</el-button
                    >
                    <el-button
                        type="primary"
                        plain
                        icon="Upload"
                        @click="handleImport"
                        v-hasPermi="['bg:file:import']"
                        >导入</el-button
                    >
                    <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['bg:file:export']"
                        >导出</el-button
                    >
                </template>
            </TableSetup>
            <auto-table
                ref="multipleTable"
                class="mytable"
                :tableData="fileList"
                :columns="columns"
                :loading="loading"
                :stripe="stripe"
                :tableHeight="tableHeight"
                @onColumnWidthChange="onColumnWidthChange"
                @onSelectionChange="handleSelectionChange"
            >
                <template #categoryName="{ row }">
                    <span>{{ row.categoryName || '-' }}</span>
                </template>
                <template #isVip="{ row }">
                    <el-tag :type="row.isVip ? 'danger' : 'success'">
                        {{ row.isVip ? 'VIP专享' : '免费' }}
                    </el-tag>
                </template>

                <template #fileType="{ row }">
                    <el-tag type="success">
                        {{ row.fileType }}
                    </el-tag>
                </template>
                <template #cover="{ row }">
                    <image-preview
                        :src="fullUrl(row.cover)"
                        v-if="row.cover"
                        :width="30"
                        :height="40"
                    />
                </template>
                <template #downloadCount="{ row }">
                    <span>{{ row.downloadCount || 0 }}</span>
                </template>
                <template #updateTime="{ row }">
                    <span>{{ parseTime(row.updateTime, '{y}-{m}-{d}') }}</span>
                </template>

                <template #operate="{ row }">
                    <el-button
                        link
                        type="primary"
                        icon="Edit"
                        @click="handleUpdate(row)"
                        v-hasPermi="['bg:file:edit']"
                        >修改</el-button
                    >
                    <el-button
                        link
                        type="primary"
                        icon="Delete"
                        @click="handleDelete(row)"
                        v-hasPermi="['bg:file:remove']"
                        >删除</el-button
                    >
                </template>
            </auto-table>
            <div class="table-pagination">
                <pagination
                    v-show="total > 0"
                    :total="total"
                    v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize"
                    @pagination="getList"
                />
            </div>
        </el-card>

        <!-- 添加或修改素材文件对话框 -->
        <el-dialog :title="title" v-model="open" width="800px" append-to-body>
            <el-form
                ref="fileRef"
                :model="form"
                :rules="rules"
                label-width="80px"
            >
                <el-form-item label="文件分类" prop="categoryId">
                    <el-tree-select
                        v-model="form.categoryId"
                        :data="categoryTreeOptions"
                        :props="{
                            value: 'id',
                            label: 'categoryName',
                            children: 'children'
                        }"
                        value-key="id"
                        placeholder="请选择文件分类"
                        check-strictly
                        clearable
                    />
                </el-form-item>

                <el-form-item label="封面" prop="cover">
                    <el-upload
                        class="cover-uploader"
                        :action="uploadUrl"
                        :headers="uploadHeaders"
                        :show-file-list="false"
                        :on-success="handleCoverSuccess"
                        :before-upload="beforeCoverUpload"
                        accept="image/*"
                    >
                        <img
                            v-if="form.cover"
                            :src="form.cover"
                            class="cover-image"
                        />
                        <el-icon v-else class="cover-uploader-icon"
                            ><Plus
                        /></el-icon>
                    </el-upload>
                    <div class="upload-tip">
                        <el-text type="info" size="small">
                            支持 JPG、PNG 格式，建议尺寸 400x300，文件大小不超过
                            2MB
                        </el-text>
                    </div>
                </el-form-item>

                <el-form-item label="详情">
                    <editor v-model="form.detail" :min-height="192" />
                </el-form-item>

                <el-form-item label="文件大小" prop="fileSize">
                    <el-input
                        v-model="form.fileSize"
                        placeholder="请输入文件大小"
                    />
                </el-form-item>

                <el-form-item label="描述标记" prop="mark">
                    <el-input
                        v-model="form.mark"
                        placeholder="请输入描述标记"
                    />
                </el-form-item>

                <el-form-item label="文件名称" prop="name">
                    <el-input
                        v-model="form.name"
                        placeholder="请输入文件名称"
                    />
                </el-form-item>

                <el-form-item label="视频文件" prop="video">
                    <el-upload
                        class="video-uploader"
                        :action="uploadUrl"
                        :headers="uploadHeaders"
                        :show-file-list="false"
                        :on-success="handleVideoSuccess"
                        :before-upload="beforeVideoUpload"
                        accept="video/*"
                    >
                        <div v-if="form.video" class="video-preview">
                            <video
                                :src="form.video"
                                controls
                                class="video-player"
                            >
                                您的浏览器不支持视频播放
                            </video>
                            <div class="video-info">
                                <el-text type="success">视频上传成功</el-text>
                                <el-button
                                    type="danger"
                                    size="small"
                                    @click.stop="removeVideo"
                                    >删除</el-button
                                >
                            </div>
                        </div>
                        <div v-else class="video-upload-area">
                            <el-icon class="video-uploader-icon"
                                ><VideoCamera
                            /></el-icon>
                            <div class="video-upload-text">
                                点击上传视频文件
                            </div>
                        </div>
                    </el-upload>
                    <div class="upload-tip">
                        <el-text type="info" size="small">
                            支持 MP4、AVI、MOV 格式，文件大小不超过 100MB
                        </el-text>
                    </div>
                </el-form-item>

                <el-form-item label="文件上传" prop="fileUrl">
                    <el-upload
                        class="upload-demo"
                        :action="uploadUrl"
                        :headers="uploadHeaders"
                        :on-success="handleUploadSuccess"
                        :before-upload="beforeUpload"
                        :show-file-list="false"
                    >
                        <el-button type="primary">选择文件</el-button>
                        <template #tip>
                            <div class="el-upload__tip">
                                支持图片(jpg/png/gif)、文档(pdf/doc/ppt)、压缩包(zip/rar)、视频(mp4/avi/mov)等格式，文件大小不超过100MB
                            </div>
                        </template>
                    </el-upload>
                    <div v-if="form.fileUrl" class="file-info">
                        <span>已上传文件：{{ form.name }}</span>
                        <el-button type="text" @click="form.fileUrl = ''"
                            >删除</el-button
                        >
                    </div>
                </el-form-item>

                <el-form-item label="VIP专享" prop="isVip">
                    <el-radio-group v-model="form.isVip">
                        <el-radio :value="false">否</el-radio>
                        <el-radio :value="true">是</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm"
                        >确 定</el-button
                    >
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 导入数据对话框 -->
        <ImportData
            v-if="openImport"
            v-model="openImport"
            tableName="bg_file"
            @success="handleImportSuccess"
        />
    </div>
</template>

<script setup name="BgFile">
import {
    listFile,
    getFile,
    delFile,
    addFile,
    updateFile,
    importFile
} from '@/api/bg/file'
import { getToken } from '@/utils/auth'
import { getCategoryTree } from '@/api/file/category'
import { listAllTable } from '@/api/system/table'
import TableSetup from '@/components/TableSetup'
import AutoTable from '@/components/AutoTable'
import ImportData from '@/components/ImportData'
import { Plus, VideoCamera } from '@element-plus/icons-vue'
const { proxy } = getCurrentInstance()

const fileList = ref([])
const categoryTreeOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')

// 文件上传相关
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + '/common/upload')
const uploadHeaders = ref({
    Authorization: 'Bearer ' + getToken()
})

// 封面图片上传处理
const handleCoverSuccess = (response, file) => {
    if (response.code === 200) {
        form.value.cover = response.url
        proxy.$modal.msgSuccess('封面上传成功')
    } else {
        proxy.$modal.msgError(response.msg || '封面上传失败')
    }
}

const beforeCoverUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) {
        proxy.$modal.msgError('只能上传图片文件!')
        return false
    }
    if (!isLt2M) {
        proxy.$modal.msgError('图片大小不能超过 2MB!')
        return false
    }
    return true
}

// 视频文件上传处理
const handleVideoSuccess = (response, file) => {
    if (response.code === 200) {
        form.value.video = response.url
        proxy.$modal.msgSuccess('视频上传成功')
    } else {
        proxy.$modal.msgError(response.msg || '视频上传失败')
    }
}

const beforeVideoUpload = (file) => {
    const isVideo = file.type.startsWith('video/')
    const isLt100M = file.size / 1024 / 1024 < 100

    if (!isVideo) {
        proxy.$modal.msgError('只能上传视频文件!')
        return false
    }
    if (!isLt100M) {
        proxy.$modal.msgError('视频大小不能超过 100MB!')
        return false
    }
    return true
}

// 删除视频
const removeVideo = () => {
    form.value.video = null
    proxy.$modal.msgSuccess('视频已删除')
}

const columns = ref([])
const stripe = ref(true)
const isTable = ref(true)
const tableHeight = ref(500)
const fullScreen = ref(false)
const openImport = ref(false)

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        name: null,
        isVip: null
    },
    rules: {
        categoryId: [
            { required: true, message: '文件分类不能为空', trigger: 'blur' }
        ],
        createBy: [
            { required: true, message: '创建者不能为空', trigger: 'blur' }
        ],
        deptId: [
            { required: true, message: '部门id不能为空', trigger: 'blur' }
        ],
        detail: [{ required: true, message: '详情不能为空', trigger: 'blur' }],
        fileSize: [
            { required: true, message: '文件大小不能为空', trigger: 'blur' }
        ],
        name: [{ required: true, message: '文件名称不能为空', trigger: 'blur' }]
    }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询素材文件列表 */
function getList() {
    loading.value = true
    listFile(queryParams.value).then((response) => {
        fileList.value = response.rows
        total.value = response.total
        loading.value = false
    })
}

/** 获取分类树选项 */
function getCategoryTreeOptions() {
    getCategoryTree().then((response) => {
        categoryTreeOptions.value = response.data
    })
}

function getColumns() {
    listAllTable({ tableName: 'bg_file' })
        .then((response) => {
            columns.value = response.data
        })
        .then(() => {
            getList()
            getCategoryTreeOptions()
        })
}

// 取消按钮
function cancel() {
    open.value = false
    reset()
}

// 表单重置
function reset() {
    form.value = {
        categoryId: null,
        cover: null,
        createBy: null,
        createTime: null,
        delFlag: null,
        deptId: null,
        detail: null,
        fileSize: null,
        id: null,
        mark: null,
        name: null,
        updateTime: null,
        video: null,
        fileUrl: null,
        fileType: null,
        downloadCount: 0,
        isVip: false
    }
    proxy.resetForm('fileRef')
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm('queryRef')
    handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id)
    single.value = selection.length != 1
    multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
    reset()
    getCategoryTreeOptions()
    open.value = true
    title.value = '添加素材文件'
}

/** 新增按钮操作 */
function handleImport() {
    openImport.value = true
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset()
    getCategoryTreeOptions()
    const bgFileId = row.id || ids.value
    getFile(bgFileId).then((response) => {
        form.value = response.data
        open.value = true
        title.value = '修改素材文件'
    })
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs['fileRef'].validate((valid) => {
        if (valid) {
            if (form.value.id != null) {
                updateFile(form.value).then((response) => {
                    proxy.$modal.msgSuccess('修改成功')
                    open.value = false
                    getList()
                })
            } else {
                addFile(form.value).then((response) => {
                    proxy.$modal.msgSuccess('新增成功')
                    open.value = false
                    getList()
                })
            }
        }
    })
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _ids = row.id || ids.value
    proxy.$modal
        .confirm('是否确认删除素材文件编号为"' + _ids + '"的数据项？')
        .then(function () {
            return delFile(_ids)
        })
        .then(() => {
            getList()
            proxy.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download(
        'bg/file/export',
        {
            ...queryParams.value
        },
        `file_${new Date().getTime()}.xlsx`
    )
}

//表格全屏
function onfullTable() {
    proxy.$refs.tSetup.onFull(proxy.$refs.fullTable.$el)
    fullScreen.value = !fullScreen.value
    updateTableHeight()
}
//表格刷新
function onRefresh() {
    getList()
}
//搜索框显示隐藏
function onSearchChange() {
    showSearch.value = !showSearch.value
}

function onStripe(val) {
    stripe.value = val
}
//改变表头数据
function onChange(val) {
    columns.value = val
}

//改变表格宽度
function onColumnWidthChange(column) {
    proxy.$refs.tSetup.tableWidth(column)
}

//更新表格高度
function updateTableHeight() {
    if (
        proxy.$refs.tSetup &&
        proxy.$refs.queryRef &&
        document.querySelector('.table-pagination')
    ) {
        if (fullScreen.value) {
            tableHeight.value = window.innerHeight - 145
        } else {
            tableHeight.value =
                window.innerHeight -
                proxy.$refs.tSetup.$el.clientHeight -
                proxy.$refs.queryRef.$el.clientHeight -
                document.querySelector('.table-pagination').clientHeight -
                220
        }
    }
}
//导入成功
function handleImportSuccess(sheetName, filedInfo, fileName) {
    let data = {
        tableName: 'bg_file',
        filedInfo: filedInfo,
        fileName: fileName,
        sheetName: sheetName
    }
    importFile(data).then(() => {
        proxy.$modal.msgSuccess('导入成功')
        openImport.value = false
        getList()
    })
    getList()
}

onMounted(() => {
    updateTableHeight() // 初始化计算高度
    window.addEventListener('resize', updateTableHeight) // 监听窗口大小变化
})

onUnmounted(() => {
    window.removeEventListener('resize', updateTableHeight) // 销毁监听
})

// 文件上传前验证
function beforeUpload(file) {
    const isValidType = [
        // 图片格式
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/bmp',
        // 文档格式
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-powerpoint',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        // 压缩格式
        'application/zip',
        'application/x-rar-compressed',
        'application/x-7z-compressed',
        // 视频格式
        'video/mp4',
        'video/avi',
        'video/quicktime',
        'video/x-msvideo',
        'video/x-ms-wmv',
        'video/x-flv',
        'video/x-matroska',
        'video/webm'
    ].includes(file.type)
    const isLt100M = file.size / 1024 / 1024 < 100

    if (!isValidType) {
        proxy.$modal.msgError('上传文件格式不正确!')
        return false
    }
    if (!isLt100M) {
        proxy.$modal.msgError('上传文件大小不能超过 100MB!')
        return false
    }
    return true
}

// 文件上传成功回调
function handleUploadSuccess(response, file) {
    if (response.code === 200) {
        form.value.fileUrl = response.url
        // form.value.name = file.name
        // form.value.fileSize = (file.size / 1024 / 1024).toFixed(2) + 'MB'
        // form.value.fileType = file.type
        proxy.$modal.msgSuccess('文件上传成功')
    } else {
        proxy.$modal.msgError(response.msg || '文件上传失败')
    }
}

getColumns()
</script>

<style scoped>
.cover-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
}

.cover-uploader:hover {
    border-color: #409eff;
}

.cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    display: block;
}

.cover-image {
    width: 128px;
    height: 178px;
    object-fit: cover;
    display: block;
}

.upload-tip {
    margin-top: 8px;
    text-align: center;
}

.file-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
    width: 100%;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.file-uploader:hover {
    border-color: #409eff;
}

.file-uploader-icon {
    font-size: 20px;
    color: #8c939d;
    margin-right: 8px;
}

.file-upload-text {
    color: #8c939d;
    font-size: 14px;
}

/* 视频上传样式 */
.video-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
    width: 100%;
}

.video-uploader:hover {
    border-color: #409eff;
}

.video-upload-area {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 120px;
    color: #8c939d;
}

.video-uploader-icon {
    font-size: 32px;
    margin-bottom: 8px;
}

.video-upload-text {
    font-size: 14px;
}

.video-preview {
    position: relative;
}

.video-player {
    width: 100%;
    max-width: 400px;
    height: 200px;
    border-radius: 6px;
    background: #000;
}

.video-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 8px;
    padding: 8px;
    background: #f5f7fa;
    border-radius: 4px;
}
</style>